﻿using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Data.Common;
using System.Collections.Generic;
using SqlSugar;
using System.Linq;
using NLog;

namespace ByteSite.DBUtility
{
    public class DbContext
    {
        private ILogger logger = LogManager.GetCurrentClassLogger();
        //数据库连接字符串(web.config来配置)，可以动态更改connectionString支持多数据库.
        public static string connectionString;
        public static string connectionProvider;
        public SqlSugarClient Db;
        public DbContext(){
            if (string.IsNullOrEmpty(connectionString))
            {
                string path = Common.Utils.GetMapPath("~/xmlconfig/db.config");
                DBConfig dbconfig = (DBConfig)Common.SerializationHelper.Load(typeof(DBConfig), path);
                if (dbconfig.Encryption == 1)
                {
                    connectionString = Common.AES.Decode(dbconfig.ConnectionString, "bytesite_ae125efkk454eeff444ferf");
                }
                else
                {
                    connectionString = dbconfig.ConnectionString;
                    string encode_str = Common.AES.Encode(dbconfig.ConnectionString, "bytesite_ae125efkk454eeff444ferf");
                }
                connectionProvider = dbconfig.Provider;
            }

            ConnectionConfig dbConfig = new ConnectionConfig();
            dbConfig.ConnectionString = connectionString;
            if (connectionProvider.ToLower() == "sqlserver")
            {
                dbConfig.DbType = SqlSugar.DbType.SqlServer;
            }
            else if (connectionProvider.ToLower() == "mysql")
            {
                dbConfig.DbType = SqlSugar.DbType.MySql;
            }
            else if (connectionProvider.ToLower() == "oracle")
            {
                dbConfig.DbType = SqlSugar.DbType.Oracle;
            }
            else if (connectionProvider.ToLower() == "sqlite")
            {
                dbConfig.DbType = SqlSugar.DbType.Sqlite;
            }
            else if (connectionProvider.ToLower() == "postgresql")
            {
                dbConfig.DbType = SqlSugar.DbType.PostgreSQL;
            }
            else
            {
                dbConfig.DbType = SqlSugar.DbType.SqlServer;
            }
            dbConfig.IsAutoCloseConnection = true;
            dbConfig.InitKeyType = InitKeyType.Attribute;

            Db = new SqlSugarClient(dbConfig);
            //Print sql
            Db.Aop.OnLogExecuting = (sql, pars) =>
            {
                Common.LoggerHelper.Info("[sql]" + sql + "\r\n" + Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)) + "\r\n");
            };
        }

    }
}
